package cn.sstir.api.service.impl;

import cn.sstir.api.common.exception.ClientNotExistException;
import cn.sstir.api.common.util.RedisUtil;
import cn.sstir.api.entity.ClientDetails;
import cn.sstir.api.mapper.ClientDetailsMapper;
import cn.sstir.api.service.ClientDetailsService;
import cn.sstir.fastspringboot.core.util.MD5Util;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.UUID;

import static cn.sstir.api.common.constants.ClientConstants.REDIS_CLIENT_PACKAGE_NAME;

/**
 * @author: fli
 * @email: fli@sstir.cn
 * @date: 2019/8/21 16:08
 */
@Service
public class ClientDetailServiceImpl extends ServiceImpl<ClientDetailsMapper, ClientDetails> implements ClientDetailsService {

    @Override
    public void saveAndSyncToRedis(ClientDetails clientDetails) {
        clientDetails.setId(null);
        clientDetails.setClientSecret(MD5Util.encrypt(UUID.randomUUID().toString()));
        super.save(clientDetails);
        RedisUtil.set(REDIS_CLIENT_PACKAGE_NAME + clientDetails.getClientId(), clientDetails);
    }

    @Override
    public void updateAndSyncToRedis(ClientDetails clientDetails) {
        clientDetails.setClientId(null);
        clientDetails.setClientSecret(null);
        if(!super.updateById(clientDetails)){
            throw new ClientNotExistException();
        }
        ClientDetails details = super.getById(clientDetails.getId());
        if (clientDetails.getStatus() == 1) {
            RedisUtil.delete(REDIS_CLIENT_PACKAGE_NAME + details.getClientId());
        } else
            RedisUtil.set(REDIS_CLIENT_PACKAGE_NAME + details.getClientId(), details);
    }

    @Override
    public void deleteAndSyncToRedis(Long id) {
        ClientDetails clientDetails = super.getById(id);
        if(null == clientDetails){
            throw new ClientNotExistException();
        }
        super.removeById(id);
        RedisUtil.delete(REDIS_CLIENT_PACKAGE_NAME + clientDetails.getClientId());

    }
}
